package sentinel

import (
	"gc-rds-ha/internal/dao"

	log "github.com/sirupsen/logrus"
	"golang.org/x/net/context"

	"gorm.io/gorm"
)

type MysqlProxyVip struct {
	dao.DefaultField

	MasterIP        string `gorm:"type:varchar(200);not null;default:'';index:master_ip_port;comment:主节点;"`
	MasterPort      uint32 `gorm:"type:int(10);not null;default:0;index:master_ip_port;comment:主节点端口;"`
	ProxyIP         string `gorm:"type:varchar(200);not null;default:'';comment:proxy节点ID，对应ecs实例ID;"`
	VipBindProxyIP  string `gorm:"type:varchar(200);not null;default:'';comment:VIP已绑定的ProxyIP;"`
	VipIP           string `gorm:"type:varchar(200);not null;default:'';comment:VIP地址;"`
	IsDiscover      uint32 `gorm:"type:tinyint(3);not null;default:0;comment:orchestrator是否discover 0否 1是;"`
	NetWorkID       string `gorm:"type:varchar(200);not null;default:'';comment:VPC ID;"`
	SubNetID        string `gorm:"type:varchar(200);not null;default:'';comment:子网 ID;"`
	AzoneCode       uint32 `gorm:"type:int(10);not null;default:0;comment:区域ID;"`
	RegionCode      uint32 `gorm:"type:int(10);not null;default:0;comment:可用区ID;"`
	ResourceGroupID string `gorm:"type:varchar(200);not null;default:'';comment:资源组ID,传所属子网的资源组ID;"`
	OwnerType       string `gorm:"type:varchar(200);not null;default:'user';comment:拥有着类型，默认user;"`
	OwnerID         string `gorm:"type:varchar(200);not null;default:'';comment:拥有者ID,默认tenantID;"`

	Tx *gorm.DB `gorm:"-"`
}

func (d *MysqlProxyVip) Model() *gorm.DB {
	db := dao.DB
	if d.Tx != nil {
		db = d.Tx
	}
	return db.Table(d.TableName()).Model(d)
}

func (d *MysqlProxyVip) TableName() string {
	tableName := "mysql_proxy_vip"
	return tableName
}

// Create 创建
func (d *MysqlProxyVip) Create(ctx context.Context) error {
	check := &MysqlProxyVip{
		MasterIP:   d.MasterIP,
		MasterPort: d.MasterPort,
	}
	if err := d.Model().FirstOrCreate(d, check).Error; err != nil {
		log.WithFields(log.Fields{"err": err, "d": d}).Error("MysqlProxyVip m.Create(d) error")
	}

	return nil
}

func CreateTableMysqlProxyVip() {
	d := &MysqlProxyVip{}
	for i := uint32(0); i < d.TableCount(); i++ {
		if err := dao.DB.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(d); err != nil {
			log.WithField("", log.Fields{"err": err, "tableName": d.TableName()}).Error("DB AutoMigrate Failed")
		}
	}
}

func (d *MysqlProxyVip) List(offset, limit int) ([]MysqlProxyVip, error) {
	var l = make([]MysqlProxyVip, 10)
	m := d.Model()
	if d.ID >= 0 {
		m = m.Where("id", d.ID)
	}

	if err := m.Order("id desc").Offset(offset).Limit(limit).Find(&l).Error; err != nil {
		log.WithFields(log.Fields{
			"d":     d,
			"error": err,
		}).Error("MysqlProxyVip.List error: ")
		return nil, err
	}
	return l, nil
}

// TableCount 分表数量
func (d *MysqlProxyVip) TableCount() uint32 {
	return 1
}
